package com.oro.validator;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

public class PartitaIvaValidator implements Validator {

	private boolean isValid(Object value) {
		if (value == null) {
			return true;
		}
		if (!(value instanceof String)) {
			return false;
		}

		String partitaIva = (String) value;
		if (partitaIva.length() == 0) {
			return true;
		}

		int i, c, s;
		if (partitaIva.length() != 11) {
			return false;
		}

		for (i = 0; i < 11; i++) {
			if (partitaIva.charAt(i) < '0' || partitaIva.charAt(i) > '9') {
				return false;
			}
		}

		s = 0;
		for (i = 0; i <= 9; i += 2) {
			s += partitaIva.charAt(i) - '0';
		}
		for (i = 1; i <= 9; i += 2) {
			c = 2 * (partitaIva.charAt(i) - '0');
			if (c > 9) {
				c = c - 9;
			}
			s += c;
		}
		return (10 - s % 10) % 10 == partitaIva.charAt(10) - '0';
	}

	@Override
	public void validate(FacesContext arg0, UIComponent arg1, Object arg2)
			throws ValidatorException {

		if (!isValid(arg2)) {
			FacesMessage message = new FacesMessage();
			message.setSummary("Partita IVA non valida.");
			throw new ValidatorException(message);
		}

	}

}
